package utils

import (
	"errors"
	"fmt"
	"time"

	"github.com/golang-jwt/jwt"
)

var jwtKey = []byte("your_jwt_secret_key") // 在实际应用中应该从配置文件读取

type Claims struct {
	UserID uint
	IsAdmin bool
	jwt.StandardClaims
}

// GenerateToken 生成 JWT token
func GenerateToken(userID uint, isAdmin bool) (string, error) {
	// 设置token的有效期为24小时
	expirationTime := time.Now().Add(24 * time.Hour)

	claims := &Claims{
		UserID: userID,
		IsAdmin: isAdmin,
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: expirationTime.Unix(),
			IssuedAt:  time.Now().Unix(),
		},
	}

	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	return token.SignedString(jwtKey)
}

// ValidateToken 验证 JWT token
func ValidateToken(tokenString string) (*Claims, error) {
	claims := &Claims{}

	token, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (interface{}, error) {
		fmt.Printf("Validating token signing method: %v\n", token.Method) // 添加调试日志
		if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
			return nil, errors.New("unexpected signing method")
		}
		return jwtKey, nil
	})

	if err != nil {
		fmt.Printf("Token parsing error: %v\n", err) // 添加调试日志
		return nil, err
	}

	if !token.Valid {
		return nil, errors.New("invalid token")
	}

	fmt.Printf("Token validated successfully for user ID: %d\n", claims.UserID) // 添加调试日志
	return claims, nil
}

// ParseToken 解析 token（如果已经存在，可以删除这个函数）
func ParseToken(tokenString string) (*Claims, error) {
	return ValidateToken(tokenString)
}
